package com.baidu.iit.pxp.handler;

import com.baidu.iit.pvm.process.ActivityImpl;
import com.baidu.iit.pxp.constants.BpmnXMLConstants;
import com.baidu.iit.pxp.event.EndEvent;
import com.baidu.iit.pxp.model.BaseElement;
import com.baidu.iit.pxp.model.ErrorEventDefinition;
import com.baidu.iit.pxp.model.EventDefinition;
import com.baidu.iit.pxp.parser.BpmnParse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 上午9:47
 */
public class EndEventParseHandler extends AbstractActivityBpmnParseHandler<EndEvent> {

    private static final Logger logger = LoggerFactory.getLogger(EndEventParseHandler.class);

    public Class<? extends BaseElement> getHandledType() {
        return EndEvent.class;
    }

    protected void executeParse(BpmnParse bpmnParse, EndEvent endEvent) {

        ActivityImpl endEventActivity = createActivityOnCurrentScope(bpmnParse, endEvent, BpmnXMLConstants.ELEMENT_EVENT_END);
        EventDefinition eventDefinition = null;
        if (endEvent.getEventDefinitions().size() > 0) {
            eventDefinition = endEvent.getEventDefinitions().get(0);
        }

        if (eventDefinition instanceof ErrorEventDefinition) {
            ErrorEventDefinition errorDefinition = (ErrorEventDefinition) eventDefinition;
            if (bpmnParse.getBpmnModel().containsErrorRef(errorDefinition.getErrorCode())) {
                String errorCode = bpmnParse.getBpmnModel().getErrors().get(errorDefinition.getErrorCode());
                if (StringUtils.isEmpty(errorCode)) {
                    logger.warn("errorCode is required for an error event " + endEvent.getId());
                }
                endEventActivity.setProperty("type", "errorEndEvent");
                errorDefinition.setErrorCode(errorCode);
            }
            endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createErrorEndEventActivityBehavior(endEvent, errorDefinition));

        } else if (eventDefinition == null) {
            endEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createNoneEndEventActivityBehavior(endEvent));
        }
    }

}
